﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Collections;

namespace Cnfi.Core
{
    /// <summary>
    /// A class to move files using ftp protocol
    ///
    /// Author: Asad 
    /// 
    /// </summary>
    public class FTPLib
    {

        string _errormessage;
        CnfiSftp _fenSftp;
        public FTPLib(string ftpServerAddress, string ftpUserID, string ftpPassWord)
        {
            FtpServerAddress = ftpServerAddress;
            FtpUserID = ftpUserID;
            FtpPassword = ftpPassWord;
            EnableSsl = false;
            SFTPIsActive = false;
        }
        public FTPLib(string ftpServerAddress, string ftpUserID, string ftpPassWord, int port, string sftpDirectoryPath = null, string localDirectoryPath = null, bool connect = true)
        {
            FtpServerAddress = ftpServerAddress;
            FtpUserID = ftpUserID;
            FtpPassword = ftpPassWord;
            _fenSftp = new CnfiSftp(ftpServerAddress, ftpUserID, ftpPassWord, port, connect);
            if (string.IsNullOrWhiteSpace(sftpDirectoryPath))
                sftpDirectoryPath = @"/";

            SftpDirectoryPath = sftpDirectoryPath;
            if (string.IsNullOrWhiteSpace(localDirectoryPath))
                LocalDirectoryPath = @"C:\";

            LocalDirectoryPath = localDirectoryPath;
            SFTPIsActive = true;
        }
        public string FtpServerAddress { get; set; }
        public string FtpUserID { get; set; }
        public string FtpPassword { get; set; }
        public bool EnableSsl { get; set; }
        public int Port { get; set; }
        public bool SFTPIsActive { get; set; }
        public string SftpDirectoryPath { get; set; }
        public string LocalDirectoryPath { get; set; }

        /// <summary>
        /// Method to upload the specified file to a specified FTP Server
        /// </summary>
        /// <param name="fullFileName">file full name to be uploaded</param>
        ///
        public bool UploadFileByFTP(string fullFileName, string serverDirectory = null)
        {
            FileInfo fileInf = new FileInfo(fullFileName);
            string uri = "ftp://" + FtpServerAddress + "/" +serverDirectory+ fileInf.Name;
            FtpWebRequest reqFTP;

            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FtpServerAddress + "/" + serverDirectory + fileInf.Name));

            // Provide the WebPermission Credintials
            reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);

            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            reqFTP.KeepAlive = false;

            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            reqFTP.UseBinary = true;

            // Notify the server about the size of the uploaded file
            reqFTP.ContentLength = fileInf.Length;

            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            FileStream fs = fileInf.OpenRead();
            Stream strm = null;
            try
            {
                // Stream to which the file to be upload is written
                strm = reqFTP.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                _errormessage = "Upload Error";

                // Close the file stream and the Request Stream
                if (strm != null) strm.Close();
                if (fs != null) fs.Close();

                return false;
            }
        }
        public bool UploadFile(string fullFileName)
        {
            if (!SFTPIsActive)
                return UploadFileByFTP(fullFileName);
            else
            {
                _fenSftp.Put(fullFileName, SftpDirectoryPath);
                return true;
            }

        }
        private void DownloadFileByFtp(string filePath, string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                //filePath = <<The full path where the file is to be created.>>,
                //fileName = <<Name of the file to be created(Need not be the name of the file on FTP server).>>
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FtpServerAddress + "/" + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (WebException e)
            {
                String status = ((FtpWebResponse)e.Response).StatusDescription;
                throw;
            }
        }
        public void DownloadFile(string filePath, string fileName)
        {
            if (!SFTPIsActive)
                DownloadFileByFtp(filePath, fileName);
            else
                _fenSftp.Get(SftpDirectoryPath + @"/" + fileName, filePath + @"/" + fileName);
        }
        public bool DeleteFileByFTP(string fileName)
        {
            try
            {
                string uri = "ftp://" + FtpServerAddress + "/" + fileName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FtpServerAddress + "/" + fileName));

                reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                _errormessage = ex.Message;
                return false;
            }
        }
        public bool DeleteFile(string fileName)
        {
            if (!SFTPIsActive)
                return DeleteFileByFTP(fileName);
            else
                return false;//Does not exist in sftp.

        }
        private string[] GetFileDetailListByFTP()
        {
            string[] downloadFiles;
            try
            {
                StringBuilder result = new StringBuilder();
                FtpWebRequest ftp;
                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FtpServerAddress + "/"));
                ftp.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }

                result.Remove(result.ToString().LastIndexOf("\n"), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
                //MessageBox.Show(result.ToString().Split('\n'));
            }
            catch (Exception ex)
            {
                // System.Windows.Forms.MessageBox.Show(ex.Message);
                downloadFiles = null;
                return downloadFiles;
            }
        }
        private string[] GetFilesDetailList()
        {
            if (!SFTPIsActive)
                return GetFileDetailListByFTP();
            else
                return (string[])_fenSftp.GetFileList(SftpDirectoryPath).ToArray(typeof(string));
        }
        public bool UploadFileTest()
        {
            FileStream aFile = null;
            StreamWriter sw = null;

            string ftpFileName = null;
            string fullFilename = null;

            try
            {
                var path = Path.GetTempPath();
                ftpFileName = @"test.txt";
                fullFilename = path + ftpFileName;

                aFile = new FileStream(fullFilename, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(aFile);
                sw.Write("Dette er en ftp upload test!");

            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                if (sw != null) sw.Close();
                if (aFile != null) aFile.Close();

            }


            UploadFile(fullFilename);

            bool verdi = DeleteFile(ftpFileName);

            return true;

        }
        public void DownloadAlleFilesByFtp(string filePath, string fileEnding)
        {
            FtpWebRequest reqFTP;
            List<string> files = new List<string>();

            try
            {
                fileEnding = fileEnding.Replace("*.", ".");
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FtpServerAddress + "/"));
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                reqFTP.EnableSsl = EnableSsl;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);

                try
                {
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        if (line.Contains(fileEnding)) files.Add(line);
                    }
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }

                reader.Close();
                response.Close();

                foreach (var item in files)
                {
                    DownloadFile(filePath, item);
                }
            }
            catch (WebException e)
            {
                String status = ((FtpWebResponse)e.Response).StatusDescription;
                throw;
            }
        }
        public void DownloadAlleFiles(string filePath, string fileEnding)
        {
            try
            {
                if (!SFTPIsActive)
                    DownloadAlleFilesByFtp(filePath, fileEnding);
                else
                {
                    string[] fromfilePath = this.GetFilesDetailList();
                    foreach (string file in fromfilePath)
                    {
                        if (file.Contains(fileEnding))
                            _fenSftp.Get(@"/" + file, filePath + @"\" + file);
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
    }
}